<template>
  <el-input
    ref="refInput"
    v-model="value"
    clearable
    @blur="myblur"
    @change="mychange"
    @input="myinput"
    @clear="myclear"
    @keydown="mykeydown"
    v-bind="$attrs"
  >
    <template 
      v-for="(item, key, index) in $slots"
        :key="index"
        v-slot:[key]
    >
      <slot :name="key"></slot>
    </template>
  </el-input>
  <div v-if="model" style="display: none;">{{model[colName]}}</div>
</template>

<script>
  import { ref, defineComponent, onMounted } from 'vue'
  import { ElInput } from 'element-plus'
  import debounceRef from '../js/debounceRef.js'
 
  export default defineComponent({
    name: '传声筒',
    inheritAttrs: false,
    props: {
      modelValue: [String, Number, Object],
      model: Object, // 表单需要的 model
      colName: String, // 要使用的属性名称
      events: Object // 事件、方法的集合
    },
    emits: ['update:modelValue'],
    setup (props, context) {
      const emit = context.emit
      const events = props.events
      const refInput = ref(null)

      // 设置方法
      events.focus = () => {
        refInput.value.focus()
      }
      onMounted(() => {
        console.log('子组件的input', refInput.value)
        // refInput.value.focus()
      })
      console.log('props：', props)
      console.log('ctx：', context)
      console.log('emit：', emit)

      const ctlEvents = {
        run: () => {},
        clear: () => {}
      }
      const value = debounceRef(props, ctlEvents, emit)

      //  
      const myinput = (val) => {
        events.myinput(val) // 立即执行
      }

      // 在点击由 clearable 属性生成的清空按钮时触发
      const myclear = () => {
        ctlEvents.run() // 立即执行
      }
 
      // 仅在输入框失去焦点或用户按下回车时触发
      const mychange = () => {
        ctlEvents.run() // 立即执行
      }
      // 在 Input 失去焦点时触发
      const myblur = () => {
        ctlEvents.run() // 立即执行
      }
      // 按键，用于汉字的连续输入
      const mykeydown = (e) => {
        // console.log('按键信息：', e)
        ctlEvents.clear()
      }

      const focus = () => {
        refInput.value.focus()
      }
      return {
        refInput,
        value,
        focus,
        myinput,
        myclear,
        mychange,
        myblur,
        mykeydown
      }
    }
  })
</script>
